<?php

namespace App\Jobs\Controller;

use App\Common\Libs\Ali\Oss;
use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalMessageConst;
use App\Consts\GlobalUploadConst;
use App\Jobs\BaseJob;
use App\Models\IndexComment;
use App\Models\UserAnnounce;
use App\Models\UserMessageCommentReceive;
use App\Models\UserMessageCommentSend;
use App\Models\UserMessageCount;
use App\Models\UserMessageLikeReceive;
use App\Models\UserMessageLikeSend;

class MessageJob extends BaseJob
{
    /**
     * 将系统消息变为已读
     * @param $userId
     * @param array $announceUserId
     * @return bool
     */
    public function changeAnnounceRead($msgContent)
    {
        $data = $msgContent['msgContent'];
        $query = UserAnnounce::getInstance($data['user_id'])
            ->where('user_id', $data['user_id']);
        if (!empty($data['announce_user_id'])) {
            $query->whereIn('announce_id', (array)$data['announce_user_id']);
        }

        $query->update(['is_read' => GlobalMessageConst::IS_READ]);

        UserMessageCount::getInstance($data['user_id'])
            ->where('user_id', $data['user_id'])
            ->whereNotNull('announce_user_id')
            ->update(['count' => 0]);

        return true;
    }

    /**
     * 修改用户未读消息数
     * @param array $data ['user_id' => '', 'message_type' => '']
     * @return bool
     */
    public function changeUnreadCount($data)
    {
        $data = $data['msgContent'];
        $userMessageCount = repository()->MessageCountRepository->getUserMsgCountByUserIdAndMsgType($data['user_id'], $data['message_type']);
        if ($userMessageCount) {
            $count = $userMessageCount->count + $data['count'];
            $count = $count < 0 ? 0 : $count;
            repository()->MessageCountRepository->updateMessageCount($userMessageCount, [
                'count' => $count
            ]);
        } else {
            repository()->MessageCountRepository->createMessageCount([
                'user_id' => $data['user_id'],
                'message_type' => $data['message_type'],
            ]);
        }

        return true;
    }

    /**
     * 保存和静态化评论/回复消息
     * @param $data
     * @return bool
     */
    public function saveAndStaticCommentMessage($data)
    {
        $data = $data['msgContent'];
        service()->MessageService->createCommentMessage($data);

        return true;
    }

    /**
     * 静态化【我收到的点赞】消息
     * @param array $data
     * @return bool
     */
    public function staticLikeMessage($data)
    {
        $data = $data['msgContent'];
        $staticMessageData = $data['static_message'];
        Oss::getInstance(GlobalUploadConst::OBJECT_LIKE_MSG_RECEIVE . $data['receive_id'] . '/')
            ->uploadTarget(ArrayHelper::merge([
                'id' => $data['message_id'],
                'created_at' => $data['created_at']
            ], $staticMessageData));

        // 将【我发出的点赞】和【我收到的点赞】记录的<is_static>字段 = 1（静态化完成）
        $msgLikeSend = repository()->LikeRepository->getLikeSendBySenderIdAndTargetId($data['sender_id'], $data['target_id']);
        repository()->LikeRepository->updateLikeSend($msgLikeSend, ['is_static' => GlobalMessageConst::IS_STATIC]);

        $msgLikeReceive = repository()->LikeRepository->getLikeReceiveByReceiveIddAndTargetId($data['receive_id'], $data['target_id']);
        repository()->LikeRepository->updateLikeReceive($msgLikeReceive, ['is_static' => GlobalMessageConst::IS_STATIC]);

        return true;
    }

    /**
     * 删除评论时，删除评论相关的消息
     * @param $data
     * @return bool
     */
    public function delCommentMessage($data)
    {
        $commentInfo = $data['msgContent'];

        $comments = IndexComment::getInstance()
            ->select(['comment_id', 'user_id', 'reply_id', 'target_id', 'target_type'])
            ->where('comment_id', $commentInfo['comment_id'])
            ->where('to_reply_id', '')
            ->get();

        $receiveUserIdArr = [];
        foreach ($comments as $comment) {
            $receiveUserId = service()->CommentService->getTargetUserId([
                'target_id' => $comment['target_id'],
                'target_type' => $comment['target_type'],
            ]);

            service()->MessageService->changeUnreadCount([
                'user_id' => $comment->user_id,
                'message_type' => GlobalMessageConst::COUNT_TYPE_COMMENT,
                'count' => GlobalCounterConst::DECREASE
            ]);

            service()->MessageService->changeUnreadCount([
                'user_id' => $receiveUserId,
                'message_type' => GlobalMessageConst::COUNT_TYPE_COMMENT,
                'count' => GlobalCounterConst::DECREASE
            ]);

            if ($receiveUserId) {
                $receiveUserIdArr[] = $receiveUserId;
            }
        }

        $replyIdArr = ArrayHelper::getColumn($comments, 'reply_id');
        $allUserIdArr = ArrayHelper::merge(ArrayHelper::getColumn($comments, 'user_id'), $receiveUserIdArr);
        $userIdTable = IdBuilder::getSubTableByArray($allUserIdArr);

        foreach ($userIdTable as $tableCount => $userIdArr) {
            UserMessageCommentSend::setTableNameByTableCount($tableCount)
                ->where('comment_id', $commentInfo['comment_id'])
                ->where('type', GlobalMessageConst::MSG_TYPE_COMMENT)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageCommentSend::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->where('type', GlobalMessageConst::MSG_TYPE_REPLY)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);


            UserMessageCommentReceive::setTableNameByTableCount($tableCount)
                ->where('comment_id', $commentInfo['comment_id'])
                ->where('type', GlobalMessageConst::MSG_TYPE_COMMENT)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageCommentReceive::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->where('type', GlobalMessageConst::MSG_TYPE_REPLY)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageLikeSend::setTableNameByTableCount($tableCount)
                ->where('target_id', $commentInfo['comment_id'])
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageLikeReceive::setTableNameByTableCount($tableCount)
                ->where('target_id', $commentInfo['comment_id'])
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);
        }

        return true;
    }

    /**
     * 删除回复时，删除回复相关的消息
     * @param $data
     * @return bool
     */
    public function delReplyMessage($data)
    {
        $replyInfo = $data['msgContent'];

        $comments = IndexComment::getInstance()
            ->select(['comment_id', 'user_id', 'reply_id', 'target_id', 'target_type'])
            ->where('reply_id', $replyInfo['reply_id'])
            ->orWhere('to_reply_id', $replyInfo['reply_id'])
            ->get();

        $receiveUserIdArr = [];
        foreach ($comments as $comment) {
            $receiveUserId = service()->ReplyService->getReplyTargetUserId([
                'target_id' => $comment['target_id'],
                'target_type' => $comment['target_type'],
            ]);
            service()->MessageService->changeUnreadCount([
                'user_id' => $comment->user_id,
                'message_type' => GlobalMessageConst::COUNT_TYPE_COMMENT,
                'count' => GlobalCounterConst::DECREASE
            ]);
            service()->MessageService->changeUnreadCount([
                'user_id' => $receiveUserId,
                'message_type' => GlobalMessageConst::COUNT_TYPE_COMMENT,
                'count' => GlobalCounterConst::DECREASE
            ]);
            if ($receiveUserId) {
                $receiveUserIdArr[] = $receiveUserId;
            }
        }

        $replyIdArr = ArrayHelper::getColumn($comments, 'reply_id');
        $allUserIdArr = ArrayHelper::merge(ArrayHelper::getColumn($comments, 'user_id'), $receiveUserIdArr);
        $userIdTable = IdBuilder::getSubTableByArray($allUserIdArr);
        foreach ($userIdTable as $tableCount => $userIdArr) {
            UserMessageCommentSend::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageCommentSend::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);


            UserMessageCommentReceive::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageCommentReceive::setTableNameByTableCount($tableCount)
                ->whereIn('reply_id', $replyIdArr)
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageLikeSend::setTableNameByTableCount($tableCount)
                ->where('target_id', $replyInfo['reply_id'])
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);

            UserMessageLikeReceive::setTableNameByTableCount($tableCount)
                ->where('target_id', $replyInfo['reply_id'])
                ->update(['is_deleted' => GlobalConst::IS_DELETED]);
        }

        return true;
    }
}
